<template>
  <div class="activity-approval">
    <el-card class="approval-card">
      <div slot="header" class="card-header">
        <span><i class="el-icon-s-check"></i> 活动审核</span>
      </div>
      
      <div class="filter-container">
        <el-input
          v-model="activityListQuery.keyword"
          placeholder="活动名称/申请社团"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleActivityFilter"
        />
        <el-input
          v-model="activityListQuery.type"
          placeholder="活动类型"
          style="width: 130px"
          class="filter-item"
          clearable
          @keyup.enter.native="handleActivityFilter"
        />
        <el-select
          v-model="activityListQuery.status"
          placeholder="审核状态"
          clearable
          style="width: 130px"
          class="filter-item"
        >
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleActivityFilter"
        >
          搜索
        </el-button>
      </div>
      
      <el-table
        :data="activityList"
        style="width: 100%"
        border
        v-loading="activityListLoading"
        fit
        highlight-current-row>
        <el-table-column prop="title" label="活动名称"  align="center">
          <template slot-scope="scope">
            <el-link type="primary" @click="openActivityDetail(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        
        <el-table-column prop="organizer" label="组织者" align="center" />
        
        <el-table-column prop="tags" label="活动类型"  align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.tags">
              <el-tag 
                v-for="(tag, index) in scope.row.tags.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="location" label="活动地点"  align="center" />
        
        <el-table-column prop="date" label="活动日期"  align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态"  align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTypeByValue(scope.row.status)">
              {{ getStatusTextByValue(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="openActivityDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="activityListQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="activityListQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="activityTotal"
        >
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 活动详情对话框 -->
    <el-dialog
      title="活动申请详情"
      :visible.sync="activityDetailVisible"
      width="70%"
      :before-close="handleCloseDialog">
      
      <div v-if="currentActivity" class="activity-detail">
        <!-- 活动基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="活动名称">{{ currentActivity.title }}</el-descriptions-item>
          <el-descriptions-item label="组织者">{{ currentActivity.organizer }}</el-descriptions-item>
          <el-descriptions-item label="最大参与人数">{{ currentActivity.maxParticipants }}</el-descriptions-item>
          <el-descriptions-item label="活动地点">{{ currentActivity.location }}</el-descriptions-item>
          <el-descriptions-item label="活动日期">{{ formatDate(currentActivity.date) }}</el-descriptions-item>
          <el-descriptions-item label="活动时间">{{ currentActivity.time }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">
            <template v-if="currentActivity.tags">
              <el-tag 
                v-for="(tag, index) in currentActivity.tags.split(',')" 
                :key="index"
                :type="getTagType(tag.trim())"
                style="margin-right: 5px; margin-bottom: 5px;">
                {{ tag.trim() }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTypeByValue(currentActivity.status)">
              {{ getStatusTextByValue(currentActivity.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活动简介" :span="2">{{ currentActivity.description }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 活动图片 -->
        <div class="detail-section">
          <h3>活动图片</h3>
          <div class="activity-image-container">
            <el-image 
              v-if="currentActivity.image" 
              :src="currentActivity.image" 
              fit="cover"
              style="width: 100%; max-width: 500px; border-radius: 4px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div v-else class="no-image">
              <i class="el-icon-picture-outline"></i>
              <span>暂无图片</span>
            </div>
          </div>
        </div>
        
        <!-- 审核意见 -->
        <div class="review-section">
          <h3>审核意见</h3>
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见（选填）"
            v-model="reviewComment">
          </el-input>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="activityDetailVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleReject(currentActivity)">拒 绝</el-button>
        <el-button type="primary" @click="handleApprove(currentActivity)">通 过</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from "@/utils/http";

export default {
  name: 'ActivityApproval',
  data() {
    return {
      // 活动列表查询参数
      activityListQuery: {
        page: 1,
        limit: 10,
        keyword: '',
        type: '',
        status: ''
      },
      // 活动列表数据
      activityList: [],
      activityTotal: 0,
      activityListLoading: true,
      
      // 活动详情对话框
      activityDetailVisible: false,
      currentActivity: null,
      reviewComment: '',
      
      // 活动安排
      activitySchedules: [
        { content: '开幕式', time: '09:00-09:30', type: 'primary' },
        { content: '主题活动', time: '09:30-11:30', type: 'success' },
        { content: '午餐休息', time: '11:30-13:00', type: 'info' },
        { content: '分组讨论', time: '13:00-15:00', type: 'warning' },
        { content: '闭幕式', time: '15:00-16:00', type: 'danger' }
      ],
      
      // 申请材料
      attachments: [
        { name: '活动策划书.docx', icon: 'el-icon-document', url: '#' },
        { name: '场地申请表.pdf', icon: 'el-icon-document', url: '#' },
        { name: '安全责任书.pdf', icon: 'el-icon-document', url: '#' },
        { name: '活动海报.png', icon: 'el-icon-picture', url: '#' }
      ]
    }
  },
  created() {
    // 检查token是否存在
    const token = localStorage.getItem('token')
    if (!token) {
      this.$router.push('/admin/login')
    }
    
    this.getActivityList();
  },
  methods: {
    // 获取待审批活动列表
    async getActivityList() {
      this.activityListLoading = true;
      
      try {
        // 调用待审批活动列表API
        const response = await httpInstance.post('/api/activity/approveList');
        
        if (response && response.code === 200) {
          // 保存数据
          const activities = response.data || [];
          
          // 应用筛选条件（如果有的话）
          let filteredData = [...activities];
          
          if (this.activityListQuery.keyword) {
            const keyword = this.activityListQuery.keyword.toLowerCase();
            filteredData = filteredData.filter(item => 
              (item.title && item.title.toLowerCase().includes(keyword)) || 
              (item.clubName && item.clubName.toLowerCase().includes(keyword))
            );
          }
          
          if (this.activityListQuery.type) {
            const type = this.activityListQuery.type.toLowerCase();
            filteredData = filteredData.filter(item => 
              item.tags && item.tags.toLowerCase().includes(type)
            );
          }
          
          if (this.activityListQuery.status) {
            filteredData = filteredData.filter(item => {
              return item.status === parseInt(this.activityListQuery.status);
            });
          }
          
          // 计算总数
          this.activityTotal = filteredData.length;
          
          // 分页
          const start = (this.activityListQuery.page - 1) * this.activityListQuery.limit;
          const end = start + this.activityListQuery.limit;
          this.activityList = filteredData.slice(start, end);
          
          console.log("获取到的待审批活动列表:", this.activityList);
        } else {
          this.$message.error(response?.msg || '获取待审批活动列表失败');
          this.activityList = [];
          this.activityTotal = 0;
        }
      } catch (error) {
        console.error('获取待审批活动列表失败:', error);
        this.$message.error('获取待审批活动列表失败，请稍后重试');
        this.activityList = [];
        this.activityTotal = 0;
      } finally {
        this.activityListLoading = false;
      }
    },
    
    // 处理筛选
    handleActivityFilter() {
      this.activityListQuery.page = 1;
      this.getActivityList();
    },
    
    // 处理每页数量变化
    handleSizeChange(val) {
      this.activityListQuery.limit = val;
      this.getActivityList();
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.activityListQuery.page = val;
      this.getActivityList();
    },
    
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger'
      };
      return statusMap[status] || 'info';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝'
      };
      return statusMap[status] || '未知';
    },
    
    // 根据活动类型返回不同的标签类型
    getTagType(type) {
      const typeMap = {
        '文化活动': 'success',
        '体育赛事': 'warning',
        '学术讲座': 'primary',
        '志愿服务': 'info',
        '招新活动': 'danger'
      };
      return typeMap[type] || '';
    },
    
    // 打开活动详情对话框
    openActivityDetail(activity) {
      this.currentActivity = activity;
      this.reviewComment = '';
      this.activityDetailVisible = true;
    },
    
    // 关闭对话框
    handleCloseDialog() {
      this.activityDetailVisible = false;
    },
    
    // 预览文件
    previewFile(file) {
      this.$message.info(`预览文件: ${file.name}`);
      // 实际项目中可以打开文件预览
    },
    
    // 审核处理（通过/拒绝）
    handleReview(activity, status) {
      const isApprove = status === 1;
      const actionText = isApprove ? '通过' : '拒绝';
      const confirmType = isApprove ? 'success' : 'warning';
      const messageType = isApprove ? 'success' : 'info';
      
      this.$confirm(`确定${actionText}"${activity.title}"的申请吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: confirmType
      }).then(async () => {
        try {
          const response = await httpInstance.post('/api/activity/approve', {
            status: status, // 1-审批通过状态，2-拒绝/撤销状态
            activityId: activity.id
          });
          
          if (response && response.code === 200) {
            this.$message[messageType](`已${actionText}"${activity.title}"的申请`);
            this.activityDetailVisible = false;
            // 更新列表
            this.getActivityList();
          } else {
            this.$message.error(response?.msg || '审批失败');
          }
        } catch (error) {
          console.error(`${actionText}活动失败:`, error);
          this.$message.error(`${actionText}失败，请稍后重试`);
        }
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 审核通过
    handleApprove(activity) {
      this.handleReview(activity, 1);
    },
    
    // 拒绝申请
    handleReject(activity) {
      this.handleReview(activity, 2);
    },
    
    // 获取状态类型
    getStatusTypeByValue(status) {
      const statusMap = {
        0: 'warning',   // 待审批
        1: 'success',   // 审批通过
        2: 'danger'     // 活动被撤销
      };
      return statusMap[status] || '';
    },
    
    // 获取状态文本
    getStatusTextByValue(status) {
      const statusMap = {
        0: '待审批',
        1: '已通过',
        2: '已拒绝'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 格式化日期（仅日期部分）
    formatDate(dateStr) {
      if (!dateStr) return '未设置';
      
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr; // 如果解析失败，返回原始值
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateStr; // 出错时返回原始值
      }
    }
  }
}
</script>

<style scoped>
.activity-approval {
  padding-bottom: 20px;
}

.filter-container {
  padding-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  padding: 15px 0;
  text-align: right;
}

/* 活动详情对话框样式 */
.activity-detail {
  margin-bottom: 20px;
}

.detail-section {
  margin-top: 30px;
}

.detail-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.detail-section p {
  line-height: 1.6;
  color: #606266;
}

.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 15px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: calc(50% - 8px);
}

.attachment-item i {
  font-size: 20px;
  margin-right: 10px;
  color: #909399;
}

.attachment-item span {
  flex: 1;
  color: #606266;
}

.review-section {
  margin-top: 30px;
}

.review-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

/* 确保对话框内容可滚动 */
.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

.activity-image-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.no-image {
  width: 100%;
  max-width: 500px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.no-image i {
  font-size: 40px;
  margin-bottom: 10px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-slot i {
  font-size: 30px;
}
</style>
